#!/bin/bash
# 一键部署脚本（服务器端执行）

echo "==================================="
echo "Apple固件监控系统 - 一键部署"
echo "==================================="
echo ""

# 检查是否为root用户
if [ "$EUID" -eq 0 ]; then 
    echo "警告: 不建议使用root用户运行"
    echo "请使用普通用户，需要权限时会提示sudo"
    exit 1
fi

# 获取当前目录
INSTALL_DIR=$(pwd)
USER=$(whoami)

echo "安装信息:"
echo "  用户: $USER"
echo "  目录: $INSTALL_DIR"
echo ""

# 1. 检测系统
echo "[1/8] 检测系统..."
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$NAME
    VER=$VERSION_ID
    echo "  系统: $OS $VER"
else
    echo "  无法检测系统版本"
    OS="Unknown"
fi

# 2. 安装Python
echo ""
echo "[2/8] 安装Python环境..."

if command -v python3 &> /dev/null; then
    PY_VERSION=$(python3 --version | cut -d' ' -f2)
    echo "  已安装 Python $PY_VERSION"
else
    echo "  正在安装Python..."
    if [[ $OS == *"Ubuntu"* ]] || [[ $OS == *"Debian"* ]]; then
        sudo apt update
        sudo apt install python3 python3-pip python3-venv -y
    elif [[ $OS == *"CentOS"* ]] || [[ $OS == *"Red Hat"* ]]; then
        sudo yum install python39 python39-pip -y
    else
        echo "  请手动安装Python 3.9+"
        exit 1
    fi
fi

# 3. 创建虚拟环境
echo ""
echo "[3/8] 创建虚拟环境..."
if [ -d "venv" ]; then
    echo "  虚拟环境已存在"
else
    python3 -m venv venv
    echo "  虚拟环境创建成功"
fi

# 激活虚拟环境
source venv/bin/activate

# 4. 升级pip
echo ""
echo "[4/8] 升级pip..."
pip install --upgrade pip -q

# 5. 安装依赖
echo ""
echo "[5/8] 安装依赖..."
if [ -f requirements.txt ]; then
    pip install -r requirements.txt -q
    echo "  依赖安装完成"
else
    echo "  错误: 找不到requirements.txt"
    exit 1
fi

# 6. 配置环境变量
echo ""
echo "[6/8] 配置环境..."

if [ -f .env ]; then
    echo "  配置文件已存在: .env"
    read -p "  是否重新配置? (y/N): " RECONFIG
    if [[ $RECONFIG =~ ^[Yy]$ ]]; then
        cp config/config.example.env .env
        echo "  请编辑 .env 文件"
        ${EDITOR:-nano} .env
    fi
else
    cp config/config.example.env .env
    echo "  已创建配置文件: .env"
    echo "  请编辑配置文件"
    ${EDITOR:-nano} .env
fi

# 7. 创建必要目录
echo ""
echo "[7/8] 创建目录..."
mkdir -p logs
chmod 755 logs
echo "  日志目录: logs/"

# 8. 测试运行
echo ""
echo "[8/8] 测试运行..."
echo "  执行单次检查..."
echo ""

python firmware_monitor.py --once

if [ $? -eq 0 ]; then
    echo ""
    echo "==================================="
    echo "部署成功！✓"
    echo "==================================="
else
    echo ""
    echo "==================================="
    echo "测试运行失败！"
    echo "==================================="
    echo ""
    echo "请检查:"
    echo "  1. .env配置是否正确"
    echo "  2. 网络连接是否正常"
    echo "  3. SMTP配置是否有效"
    exit 1
fi

# 9. 配置systemd服务
echo ""
echo "下一步: 配置后台运行"
echo ""
read -p "是否配置systemd服务? (y/N): " SETUP_SERVICE

if [[ $SETUP_SERVICE =~ ^[Yy]$ ]]; then
    echo ""
    echo "创建systemd服务文件..."
    
    SERVICE_FILE="/etc/systemd/system/firmware-monitor.service"
    
    sudo tee $SERVICE_FILE > /dev/null << EOF
[Unit]
Description=Apple Firmware Signing Monitor
After=network.target

[Service]
Type=simple
User=$USER
WorkingDirectory=$INSTALL_DIR
Environment="PATH=$INSTALL_DIR/venv/bin"
ExecStart=$INSTALL_DIR/venv/bin/python $INSTALL_DIR/firmware_monitor.py

Restart=always
RestartSec=10

StandardOutput=append:$INSTALL_DIR/logs/monitor.log
StandardError=append:$INSTALL_DIR/logs/error.log

[Install]
WantedBy=multi-user.target
EOF

    echo "  服务文件已创建: $SERVICE_FILE"
    
    # 重载systemd
    sudo systemctl daemon-reload
    
    # 启用服务
    sudo systemctl enable firmware-monitor
    echo "  已启用开机自启"
    
    # 启动服务
    sudo systemctl start firmware-monitor
    echo "  已启动服务"
    
    # 查看状态
    echo ""
    sudo systemctl status firmware-monitor --no-pager
    
    echo ""
    echo "==================================="
    echo "服务配置完成！"
    echo "==================================="
    echo ""
    echo "常用命令:"
    echo "  查看状态: sudo systemctl status firmware-monitor"
    echo "  查看日志: sudo journalctl -u firmware-monitor -f"
    echo "  停止服务: sudo systemctl stop firmware-monitor"
    echo "  重启服务: sudo systemctl restart firmware-monitor"
    echo ""
else
    echo ""
    echo "==================================="
    echo "手动运行方式"
    echo "==================================="
    echo ""
    echo "方式1: 前台运行（测试）"
    echo "  source venv/bin/activate"
    echo "  python firmware_monitor.py"
    echo ""
    echo "方式2: screen后台运行"
    echo "  screen -S monitor"
    echo "  source venv/bin/activate"
    echo "  python firmware_monitor.py"
    echo "  # 按 Ctrl+A, D 断开"
    echo ""
    echo "方式3: nohup后台运行"
    echo "  source venv/bin/activate"
    echo "  nohup python firmware_monitor.py > logs/monitor.log 2>&1 &"
    echo ""
fi

echo ""
echo "查看完整文档:"
echo "  cat docs/DEPLOYMENT_GUIDE.md"
echo ""
echo "感谢使用！"

